package com.young.mylib.asynServer.asynHttpServer;

import android.content.Context;
import android.util.Log;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.young.mylib.asynServer.asynHttpServer.entity.AsynSession;
import com.young.mylib.asynServer.asynHttpServer.impl.AsynHttpServerRequestCallback;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;

import fi.iki.elonen.NanoHTTPD;

/**
 * Created by Young on 2018/10/18.
 */

public class AsynHttpServer extends NanoHTTPD {
    private final static String TAG = "MyHttpServer";

    final Map<String, AsynHttpServerRequestCallback> mPostActions = new HashMap<>();

    public enum Status implements NanoHTTPD.Response.IStatus {

        NOT_USE_POST(700, "not use post");

        private final int requestStatus;
        private final String description;

        Status(int requestStatus, String description) {
            this.requestStatus = requestStatus;
            this.description = description;
        }

        @Override
        public String getDescription() {
            return null;
        }

        @Override
        public int getRequestStatus() {
            return 0;
        }
    }

    public AsynHttpServer( int port) {
        super(port);

    }

    @Override
    public Response serve(IHTTPSession session) {
        JSONObject responseJson = new JSONObject();
        responseJson.put("status", Constants.HTTP_RESPONSE_STATUS_OK);
        responseJson.put("data", new JSONArray());
        if (Method.POST.equals(session.getMethod())) {
            String strUri = session.getUri();
            if (mPostActions.containsKey(strUri)) {
                AsynSession session1=new AsynSession();
                session1.session=session;
                session1.bodyStr=parseBody(session);
                return mPostActions.get(strUri).onRequest(session1);
            }
        }
        return newFixedLengthResponse(Status.NOT_USE_POST, "text/json", responseJson.toJSONString());
    }

    public void post(String regex, AsynHttpServerRequestCallback callback) {
        addPostAction(regex, callback);
    }

    private void addPostAction(String regex, AsynHttpServerRequestCallback callback) {
        synchronized (mPostActions) {
            mPostActions.put(regex, callback);
        }
    }

    private String parseBody(NanoHTTPD.IHTTPSession session) {
        String body = "";
        try {
            InputStream is = session.getInputStream();
            if (is == null) {
                Log.i(TAG, "session.getInputStream() is null!");
                return body;
            }
        //    System.out.println("getInputStream not null");
            // 假定消息不超过8192byte
            int bufsize = 8192;

            byte[] buf = new byte[bufsize];

            int rlen = is.read(buf, 0, bufsize);

            if (rlen <= 0) {
                Log.i(TAG, "http body read 0 byte!");
                return body;
            }

            ByteArrayInputStream hbis = new ByteArrayInputStream(buf, 0, rlen);
            BufferedReader hin = new BufferedReader(new InputStreamReader(hbis));
            body = hin.readLine();
            body = body.replace("\\", "").trim();
            return body;
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
        return body;
    }
}
